package rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerDemo {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("43.138.188.168");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("study");
        connectionFactory.setPassword("study");
        connectionFactory.setVirtualHost("study");
        Connection connection = connectionFactory.newConnection();
        //2.开启信道
        Channel channel = connection.createChannel();
        //3.生命队列
        channel.queueDeclare("demo1",true,false,false,null);
        //4.消费消息
        /**
         * basicConsume(String queue, boolean autoAck, Consumer callback)
         * queue：队列名称
         * autoAck：是否自动确认
         * callback：接收消息后，执行的逻辑
         */
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            //接收到队列消息就会执行的方法
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到消息：" + new String(body));
            }
        };
        channel.basicConsume("demo1",true,consumer);
        //5.释放资源
        /*channel.close();
        connection.close();*/
    }

}
